package service

import (
	"egin/app/models"
	"egin/app/request"
	"egin/pkg/database"
	"egin/pkg/utils"
	"errors"
	"strings"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"gorm.io/gorm"
)

/**
*GetMemberList 获取管理员列表数据
*@return database.Paginate 数据（分页）
*@return error 错误
 */
func GetMemberList(c *gin.Context) (*database.Paginate, error) {
	memberobj := database.Db()
	if username := c.PostForm("username"); username != "" {
		memberobj = memberobj.Where("username = ?", username)
	}

	if name := c.PostForm("name"); name != "" {
		memberobj = memberobj.Where("real_name = ?", name)
	}

	if email := c.PostForm("email"); email != "" {
		memberobj = memberobj.Where("email = ?", email)
	}

	if mobile := c.PostForm("mobile"); mobile != "" {
		memberobj = memberobj.Where("mobile = ?", mobile)
	}

	if status := c.PostForm("status"); status != "" {
		memberobj = memberobj.Where("status = ?", status)
	}

	var list []models.Member
	p := &database.Paginate{}

	err := memberobj.Preload("Role", func(db *gorm.DB) *gorm.DB {
		return db.Select("id,name")
	}).Order("id desc").Scopes(p.Paginates(c)).Find(&list).Error
	if err != nil {
		zap.L().Error("GetMemberList", zap.Error(err))
		return nil, err
	}
	p.List = list
	return p, err
}

/**
*GetMember 获取管理员数据
*@return models.Member数据
*@return error 错误
 */
func GetMember(id string) (*models.Member, error) {

	var list *models.Member
	err := database.Db().Where("id = ?", id).Find(&list).Error
	if err != nil {
		zap.L().Error("GetMemberList", zap.Error(err))
		return nil, err
	}
	return list, err
}

/**
*GetMember 获取管理员数据
*@return models.Member数据
*@return error 错误
 */
func GetMemberAndRole(id string) (*models.Member, error) {

	var list *models.Member
	err := database.Db().Preload("Role", func(db *gorm.DB) *gorm.DB {
		return db.Select("id,name")
	}).Where("id = ?", id).Find(&list).Error
	if err != nil {
		zap.L().Error("GetMemberList", zap.Error(err))
		return nil, err
	}
	return list, err
}

/**
*MemberAdd 添加管理员
*@param param  request.MemberQs 绑定的请亲数据
*@return error
 */
func MemberAdd(param request.MemberQs) error {
	password, err := utils.PasswordHash(param.Password)
	if err != nil {
		return err
	}

	roleArr := strings.Split(param.Role, ",")
	var roleList []models.Role
	for _, v := range roleArr {
		if v != "" {
			roleList = append(roleList, models.Role{
				ID: utils.StrToUInt(v),
			})
		}
	}
	member := models.Member{
		Username: param.Username,
		Email:    param.Email,
		Mobile:   param.Phone,
		RealName: param.Name,
		Password: password,
		Sex:      param.Sex,
		Status:   param.Status,
		Role:     roleList,
	}

	result := database.Db().Create(&member)
	return result.Error
}

/**
*MemberEdit 修改管理员
*@param param  request.MemberQs 绑定的请亲数据
*@return error
 */
func MemberEdit(param request.MemberEditQs) error {
	roleArr := strings.Split(param.Role, ",")
	var roleList []models.Role
	for _, v := range roleArr {
		if v != "" {
			roleList = append(roleList, models.Role{
				ID: utils.StrToUInt(v),
			})
		}
	}

	var member models.Member
	database.Db().Where("id = ?", param.Id).First(&member)

	database.Db().Model(&member).Association("Role").Clear()

	member.Username = param.Username
	member.RealName = param.Name
	member.Mobile = param.Phone
	member.Email = param.Email
	member.Sex = param.Sex
	member.Status = param.Status
	member.Role = roleList

	result := database.Db().Save(&member)
	return result.Error
}

/**
*MemberDelete 删除管理员
*@return error
 */
func MemberDelete(c *gin.Context) error {
	id := c.Param("id")
	var member models.Member
	database.Db().Where("id = ?", id).First(&member)
	database.Db().Model(&member).Association("Role").Clear()

	err := database.Db().Delete(&member).Error
	return err
}

/**
*MemberUserInfo 基本信息修改
*@param param  request.MemberQs 绑定的数据
*@return error
 */
func MemberUserInfo(param request.MemberEditQs) error {

	var member models.Member
	database.Db().Where("id = ?", param.Id).First(&member)

	member.Username = param.Username
	member.RealName = param.Name
	member.Mobile = param.Phone
	member.Email = param.Email
	member.Sex = param.Sex

	result := database.Db().Save(&member)
	return result.Error
}

func MemberUserPwd(param request.MemberPwd) error {

	var member models.Member
	database.Db().Where("id = ?", param.Id).First(&member)

	res := utils.PasswordVerify(param.OldPassword, member.Password)
	if !res {
		return errors.New("原密码错误")
	}
	password, err := utils.PasswordHash(param.Password)
	if err != nil {
		return errors.New("修改失败")
	}
	member.Password = password

	result := database.Db().Save(&member)
	if result.Error != nil {
		return errors.New("修改失败")
	}
	return nil
}
